<template>
  <div>
    <van-cell v-for="(item, index) in suggestions" :key="index" icon="search"
      @click="onClickItem(item)"
    >
     <template #title>
       <div v-html="formatStr(item)"></div>
     </template>
    </van-cell>
    <!-- 搜索提示 -->
    <van-empty v-if="!suggestions.length" image="search" description="暂无建议" />
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search.js'
import { Toast } from 'vant'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },

  data () {
    return {
      suggestions: []
    }
  },

  watch: {
    searchText: {
      immediate: true, // 首次监听
      handler (newVal) {
        // 防抖
        this.setId && clearTimeout(this.setId)
        this.setId = setTimeout(() => {
          this.loadSuggestion()
        }, 800)
      }
    }
  },

  created () {

  },

  // 组件销毁前 清除定时器
  deforeDestroy () {
    clearTimeout(this.setId)
  },

  methods: {
    // 加载搜索建议
    async loadSuggestion () {
      try {
        const { options: res } = await getSuggestion(this.searchText)
        console.log(res)
        this.suggestions = res
      } catch (err) {
        Toast('获取联想建议失败')
      }
    },
    // 处理高亮文字
    formatStr (str) {
      const reg = new RegExp(this.searchText, 'gi')
      return str.replace(reg, `<span style="color:red">${this.searchText}</span>`)
    },
    // 点击 建议的每一项
    onClickItem (it) {
      this.$emit('clickItem', it)
    }
  }
}
</script>

<style scoped>

</style>
